﻿// Copyright (c) 2015, Microsoft Corporation
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Core;

namespace MyLivingRoom.Services
{
    public class CoreDispatcherService : IDispatcherService
    {
        private CoreDispatcher _dispatcher;

        public CoreDispatcherService(CoreDispatcher dispatcher)
        {
            _dispatcher = dispatcher;
        }

        public Task DispatchAsync(Action action)
        {
            return _dispatcher
                .RunAsync(CoreDispatcherPriority.Normal, () => action())
                .AsTask();
        }

        public async Task<T> DispatchAsync<T>(Func<T> func)
        {
            var result = default(T);
            await this.DispatchAsync(() => result = func());
            return result;
        }

        public Task ExecuteOrDispatchAsync(Action action)
        {
            if (this.HasThreadAccess)
            {
                action();
                return Task.CompletedTask;
            }

            return this.DispatchAsync(action);
        }

        public Task<T> ExecuteOrDispatchAsync<T>(Func<T> func)
        {
            return this.HasThreadAccess
                ? Task.FromResult(func())
                : this.DispatchAsync(func);
        }

        public bool HasThreadAccess
        {
            get { return _dispatcher.HasThreadAccess; }
        }
    }
}
